<?php
require_once 'utilities/sessions.php';
require_once 'includes/access.php';
require_once 'includes/html.php';
require_once 'includes/menu.php';
class contractView{
	
	private $lang = '';
	
	public function __construct(){
		$this->lang = $this->getLanguage();	
	}
	
	public function getLanguage(){
		$lang = sessions::getSessionByName();
		if (file_exists('language/contract_'.$lang.'.php')){
			require_once 'language/contract_'.$lang.'.php';
		}else{
			require_once 'language/contract_en.php';
		}
		return $lang;
	}
	public function showContractByCustomer( &$lists ){
	?>
		<?php 
		$list = $lists['contact'];
		$user = sessions::getSession();
		if ( empty($user) ){
			Access::setRedirect("index.php");
		}
		HTML::topHTML('Contract');
		?>
		<link rel="stylesheet" href="<?php echo WROOT?>views/js/framework/themes/base/jquery.ui.all.css">		
		<script src="<?php echo WROOT?>views/js/framework/external/jquery.bgiframe-2.1.2.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.core.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.widget.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.mouse.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.button.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.draggable.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.position.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.resizable.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.ui.dialog.js"></script>
		<script src="<?php echo WROOT?>views/js/framework/ui/jquery.effects.core.js"></script>
		<script>
		$(function(){
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
			
			var conName = $( "#conName" ),
				id = $( "#idContract" ),
				customer = $("#customer"),				
				conStartDate = $("#conStartDate"),
				conEndDate = $( "#conEndDate" ),
				description = $( "#description" ),				
				allFields = $( [] ).add( conName ).add( id ).add( conStartDate ).add( conEndDate ).add( description ).add( customer ),
				tips = $( ".validateTips" );

			function updateTips( t ) {
				tips
					.text( t )
					.addClass( "ui-state-highlight" );
				setTimeout(function() {
					tips.removeClass( "ui-state-highlight", 1500 );
				}, 500 );
			}

			function checkLength( o, n, min, max ) {
				if ( o.val().length > max || o.val().length < min ) {
					o.addClass( "ui-state-error" );
					updateTips( "Length of " + n + " must be between " +
						min + " and " + max + "." );
					return false;
				} else {
					return true;
				}
			}

			function checkRegexp( o, regexp, n ) {
				if ( !( regexp.test( o.val() ) ) ) {
					o.addClass( "ui-state-error" );
					updateTips( n );
					return false;
				} else {
					return true;
				}
			}
			function checkCharacter( sel ){
				if ( sel.val() == "" ){
					sel.addClass( "ui-state-error" );
					sel.focus();
					return false;
				}else{
					return true;
				}
			}
			function checkCharacterHtml( sel ){
				if ( sel.text() == "" ){
					sel.addClass( "ui-state-error" );
					sel.focus();
					return false;
				}else{
					return true;
				}
			}
			
			$( "#dialog-form" ).dialog({
				autoOpen: false,
				height: 400,
				width: 400,
				modal: true,
				buttons: {
					"Save": function() {
						var bValid = true;
						allFields.removeClass( "ui-state-error" );										
						bValid = bValid && checkCharacter( conName );
						bValid = bValid && checkCharacter( conStartDate );	
						bValid = bValid && checkCharacter( conEndDate );	
						//bValid = bValid && checkCharacterHtml( description );	
						
						
						//bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
						// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
						//bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
						//bValid = bValid && checkRegexp( username, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );												
						if ( bValid ){																					
							var urls = "<?php echo WROOT?>views/contract/ajaxContract.php";							
							msg = $.ajax({
								  url: urls+"?contract=add&id="+id.val()+"&conName="+conName.val()+"&conStartDate="+conStartDate.val()+"&conEndDate="+conEndDate.val()+"&description="+description.text()+"&customer="+customer.val(),								  
							      global: false,
							      type: "POST",
							      async:false,
							      success: function(msg){
//							      	alert(msg);							     								    
						        	 return msg;
							      }
							}).responseText;							
							if (eval(msg) > 0){								
								if (id.val() == 0){
									$( "#contractByCustomer tbody" ).append( "<tr id='contract"+msg+"'>" +
										"<td>" + conName.val() + "</td>" + 
										"<td>" + conStartDate.val() + "</td>" + 
										"<td>" + conEndDate.val() + "</td>" +										
										"<td style='display: none'><a href='#' id="+msg+">Edit</a></td>" +
									"</tr>" );									
								}else{																					
									$( "#contract"+id.val() ).each(function (){																			
										$( this ).find("td:eq(0)").text(conName.val());
										$( this ).find("td:eq(1)").text(conStartDate.val());										
										$( this ).find("td:eq(2)").text(conEndDate.val());
										//$( this ).find("td:eq(3)").text(description.text());
										$( this ).find("td:eq(4)").text(id.val());										
									});																
								}				
								$('#contractByCustomer tbody tr').click(function(){			        	
					        		editContract( row_mousedown($(this)) );
								});
								$('#contractByCustomer tbody tr').mouseover(function(){
									row_mouseover($(this));
								});
								
								$('#contractByCustomer tbody tr').mouseout(function(){
									row_mouseout($(this));
								});				
							}	
							$( "#idContract" ).val(0);	
							customerClose = $("#customer").val();						
				        	$( this ).dialog( "close" );				        	
				        	$("#customer option[value='"+customerClose+"']").attr("selected", "selected");					
						}
						
					},
					Cancel: function() {
						$( "#idContract" ).val(0);	
						customerClose = $("#customer").val();			
						$( this ).dialog( "close" );										
						$("#customer option[value='"+customerClose+"']").attr("selected", "selected");		
					}
				},
				close: function() {
					$( "#idContract" ).val(0);
					customerClose = $("#customer").val();					
					allFields.val( "" ).removeClass( "ui-state-error" );
					$("#customer option[value='"+customerClose+"']").attr("selected", "selected");
				}
			});

			$( "#create-user" )
				.button()
				.click(function() {
					$( "#dialog-form" ).dialog( "open" );
			});			
		});
		
		function getContractByCustomer(val){
			var urls = "<?php echo WROOT?>views/contract/ajaxContract.php";			
			$.ajax({
				  url: urls+"?contract=showByCustomer&idCustomer="+val,								  
			      global: false,
			      type: "POST",
			      async:false,
			      success: function(msg){							     
		        	if (msg != ""){
						$("#contractByCustomer tbody").html(msg);
			        }else{
			        	$("#contractByCustomer tbody").html("");
			        }
		        	$("#users-contain").attr('style', 'display : block');
		        	
		        	$('#contractByCustomer tbody tr').click(function(){			        	
		        		editContract( row_mousedown($(this)) );
					});
					$('#contractByCustomer tbody tr').mouseover(function(){
						row_mouseover($(this));
					});
					
					$('#contractByCustomer tbody tr').mouseout(function(){
						row_mouseout($(this));
					});
			      }
			});
		}
		function editContract(sel){			
			$( "#idContract" ).val(sel);			
			$( "#dialog-form" ).dialog( "open" );
			var urls = "<?php echo WROOT?>views/contract/ajaxContract.php";
			$.ajax({
			  url: urls+"?contract=getContract&id="+sel,
		      global: false,
		      type: "POST",
		      async:false,
		      dataType: 'json',
		      success: function(msg){
			      //alert("POSTID: "+msg.contactname);			
				 $("#conName").val(msg.con_name);				 			     	        	         	 	        	
	        	 $("#conStartDate").val(msg.con_datestart);  
	        	 $("#conEndDate").val(msg.con_dateend);
	        	 $("#description").val(msg.description); 	 	        	     	   	    
		      }
			});  
		}
		</script>
		<style>
			/*body { font-size: 62.5%; }*/
			label, input { display:block; }
			input.text { margin-bottom:12px; width:95%; padding: .4em; }
			fieldset { padding:0; border:0; margin-top:25px;font-size: 70.5%; }
			h1 { font-size: 1.2em; margin: .6em 0; }
			div#users-contain { width: 99%; margin: 20px 0; }
			div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
			div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
			.ui-dialog .ui-state-error { padding: .3em; }
			.validateTips { border: 1px solid transparent; padding: 0.3em; }
		</style>
		<?php		
		HTML::wrapperHeaderHTML(); 
		HTML::headerHTML( $user['name'] );
		$javaScript = "onChange='getContractByCustomer(this.value);return false'";		
		?>
		<div id="userRegistration" style="text-align: left;">
			<table border="0" cellpadding="2" cellspacing="0">
			<tbody>
				<tr>
					<td>Customer</td>
					<td><?php echo HTML::selectBox('customer', $list, true, 0, false, $javaScript)?></td>
				</tr>
			</tbody>
			</table>
			<div id="users-contain" style="display: none" class="ui-widget">
				<button id="create-user">Add Contract</button>
				<table id="contractByCustomer" class="ui-widget ui-widget-content" width="100%">
				<thead>
					<tr class="ui-widget-header">
						<th>Name</th>
						<th>Start Date</th>
						<th>End date</th>						
						<th style="display: none"></th>					
					</tr>
				</thead>
				<tbody>
				</tbody>
				</table>
			</div>
			<div id="dialog-form" title="Add Contract">
				<?php $this->htmlFormContract( $lists['posts'] )?>
			</div>
		</div>
		<?php 
		HTML::wrapperFooterHTML();
		menu::mainmenu( $this->lang );
		?>
	<?php 
	}
	public function htmlFormContract( &$lists ){
	?>
		<div id="userRegistration" style="text-align: left;">
			<fieldset>
										
			<table border="0" cellpadding="2" cellspacing="0">
			<tbody>
				<tr>
					<td ><?php echo CONTRACT_NAME?></td>
					<td><input type="text" name="conName" value="" id="conName" /></td>
				</tr>
				<tr>
					<td><?php echo CONTRACT_START_DATE?></td>
					<td><?php echo HTML::getCalendar($this->lang, 'conStartDate', '', true);?></td>
				</tr>
				<tr>
					<td><?php echo CONTRACT_END_DATE?></td>
					<td><?php echo HTML::getCalendar($this->lang, 'conEndDate', '', false);?></td>
				</tr>
				<tr>
					<td valign="top"><?php echo CONTRACT_DESCRIPTION?></td>							
					<td>
						<textarea name="description" id="description" cols="40" rows="2"></textarea>							
					</td>					
				</tr>
			</tbody>
			</table>
					
			</fieldset>				            
            <input type="hidden" id="idContract" name="idContract" value="0">	
		</div>
	<?php 
	}
}
?>